import { useEffect, useState } from "react";
import { msg, processReq } from "@/utils/util";
import { useNavigate } from "react-router-dom";

export function useRequest(
  reqFn,
  {
    defaultData,
    initLoading = false,
    manual = false,
    onSuccess = () => {},
    onFail = () => {},
    showMsgIfError = true,
  } = {},
) {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(initLoading);
  const [error, setError] = useState(null);
  const [data, setData] = useState(defaultData);
  const [args, setArgs] = useState();

  async function run(...params) {
    if (typeof reqFn !== "function") {
      throw new TypeError("参数1需要是function");
    }
    setArgs(params);
    setLoading(true);
    const [err, data] = await processReq(reqFn(...params));
    setLoading(false);
    if (err) {
      showMsgIfError && msg.error(err);
      setError(err);
      onFail(err);
      return;
    }
    setData(data);
    onSuccess(data, ...params);
  }

  async function refresh() {
    run(...args);
  }

  useEffect(() => {
    if (manual) return;
    run();
  }, []);

  return {
    loading,
    error,
    data,
    run,
    refresh,
  };
}
